package cn.edu.scau.service.impl;

import cn.edu.scau.common.setting.CommonConst;
import cn.edu.scau.common.utils.ApiResponse;
import cn.edu.scau.common.utils.TimeUtils;
import cn.edu.scau.pojo.vo.*;
import cn.edu.scau.repository.EmployeeRepository;
import cn.edu.scau.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @description:
 * @author: yuxiang
 * @create: 2021-03-30 16:17
 **/
@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeRepository employeeRepository;


    @Override
    public ApiResponse getAmountCount() {
        ApiResponse response = new ApiResponse();
        try {
            Map map = new HashMap();
            //查询员工总数(没被雇佣的)
            Long existNum = employeeRepository.countAllByDateOfTerminationIsNull();
            //查询增长率
            Long sum = employeeRepository.count();
            //今年人数(新进人数)
            Long thisYearSum = employeeRepository.countAllByDateOfHireAfter(TimeUtils.getDIYDate("2017-01-01", "yyyy-MM-dd"));
            Long lastYearSum = employeeRepository.countAllByDateOfHireAfter(TimeUtils.getDIYDate("2016-01-01", "yyyy-MM-dd"));
            //计算分数
            String growthRate = getRate(thisYearSum, lastYearSum);
            //查询流出人数
            Long drain = sum - existNum;
            map.put("exist", existNum);
            map.put("rate", growthRate);
            map.put("new", thisYearSum);
            map.put("drain", drain);
            response.setMsg("查询成功");
            response.setObj(map);
        } catch (Exception e) {
            e.printStackTrace();
            return new ApiResponse(-1, "数据库操作错误");
        }
        return response;
    }

    @Override
    public ApiResponse getTalentFlow(String time) {
        ApiResponse response = new ApiResponse();
        if (!TimeUtils.isDatePattern(time)) {
            return new ApiResponse(-1, "时间数据不对");
        }
        Date startTime = TimeUtils.getDateByString(time);
        //年尾时间
        LocalDateTime ldTime = TimeUtils.asLocalDateTime(startTime);
        ldTime = ldTime.plusMonths(12);//加12个月
        Date endTime = TimeUtils.asDate(ldTime);
        List<ChartVO> vos = employeeRepository.countYearTerm(startTime, endTime);
        response.setMsg("查询成功");
        response.setObj(vos);
        return response;
    }

    @Override
    public ApiResponse getHRData() {
        ApiResponse response = new ApiResponse();
        try {
            List<HrSourceVo> vos = new ArrayList<>();

            //总人数
            Long existNum = employeeRepository.countAllByDateOfTerminationIsNull();
            //查询增长率
            Long sum = employeeRepository.count();
            //新进人数
            Long thisYearHire = employeeRepository.countAllByDateOfHireBetween(TimeUtils.getDIYDate("2018-01-01", "yyyy-MM-dd"), CommonConst.currentSysDate);
            Long lastYearHire = employeeRepository.countAllByDateOfHireBetween(TimeUtils.getDIYDate("2017-01-01", "yyyy-MM-dd"), TimeUtils.getDIYDate("2018-01-01", "yyyy-MM-dd"));
            Long thisMonthHire = employeeRepository.countAllByDateOfHireBetween(TimeUtils.getDIYDate("2018-12-01", "yyyy-MM-dd"), CommonConst.currentSysDate);
            Long lastMonthHire = employeeRepository.countAllByDateOfHireBetween(TimeUtils.getDIYDate("2018-11-01", "yyyy-MM-dd"), TimeUtils.getDIYDate("2018-12-01", "yyyy-MM-dd"));


            //离职人数
            Long lastYearTerm = employeeRepository.countAllByDateOfTerminationIsNotNullAndAndDateOfTerminationBetween(TimeUtils.getDIYDate("2017-01-01", "yyyy-MM-dd"), TimeUtils.getDIYDate("2018-01-01", "yyyy-MM-dd"));
            Long thisYearTerm = employeeRepository.countAllByDateOfTerminationIsNotNullAndAndDateOfTerminationBetween(TimeUtils.getDIYDate("2018-01-01", "yyyy-MM-dd"), CommonConst.currentSysDate);
            Long thisMonthTerm = employeeRepository.countAllByDateOfTerminationIsNotNullAndAndDateOfTerminationBetween(TimeUtils.getDIYDate("2018-12-01", "yyyy-MM-dd"), CommonConst.currentSysDate);
            Long lastMonthTerm = employeeRepository.countAllByDateOfTerminationIsNotNullAndAndDateOfTerminationBetween(TimeUtils.getDIYDate("2018-11-01", "yyyy-MM-dd"), TimeUtils.getDIYDate("2018-12-01", "yyyy-MM-dd"));

            //人均工资
            Double avgSaraly = employeeRepository.avgSalaryAll();
            //查询流出人数
            Long drain = sum - existNum;

            //新进人数
            Map mapMonth2 = getRateMap(thisMonthHire, lastMonthHire);
            Map mapYear2 = getRateMap(thisYearHire, lastYearHire);
            //离职人员
            Map mapMonth3 = getRateMap(thisMonthTerm, lastMonthTerm);
            Map mapYear3 = getRateMap(thisYearTerm, lastYearTerm);
            HrSourceVo vo1 = new HrSourceVo("在职人数", existNum, (String) mapMonth2.get("rate"), (int) mapMonth2.get("lift"), (String) mapYear2.get("rate"), (int) mapYear2.get("lift"));
            HrSourceVo vo2 = new HrSourceVo("新进人员", thisYearHire, (String) mapMonth2.get("rate"), (int) mapMonth2.get("lift"), (String) mapYear2.get("rate"), (int) mapYear2.get("lift"));
            HrSourceVo vo3 = new HrSourceVo("离职人数", drain, (String) mapMonth3.get("rate"), (int) mapMonth3.get("lift"), (String) mapYear3.get("rate"), (int) mapYear3.get("lift"));
            HrSourceVo vo4 = new HrSourceVo("人均工资", new Double(avgSaraly).longValue(), "1.5%", 1, "0.3%", 0);

            vos.add(vo1);
            vos.add(vo2);
            vos.add(vo3);
            vos.add(vo4);
            response.setMsg("查询成功");
            response.setObj(vos);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }

    @Override
    public ApiResponse getRecruitNumber() {
        ApiResponse response = new ApiResponse();
        try {
            //全部部门
            List<String> deps = employeeRepository.selectAllDepartment();
            List<RecruitNumberVo> vos = new ArrayList<>();
            for (int i = 0; i < deps.size(); i++) {
                String dep = deps.get(i);
                //第一年
                Long y1 = employeeRepository.countAllByDateOfHireBetweenAndDepartmentEquals(TimeUtils.getDIYDate("2016-01-01", "yyyy-MM-dd"),TimeUtils.getDIYDate("2017-01-01", "yyyy-MM-dd"),dep);
                //第二年
                Long y2 = employeeRepository.countAllByDateOfHireBetweenAndDepartmentEquals(TimeUtils.getDIYDate("2017-01-01", "yyyy-MM-dd"),TimeUtils.getDIYDate("2018-01-01", "yyyy-MM-dd"),dep);
                //第三年
                Long y3 = employeeRepository.countAllByDateOfHireBetweenAndDepartmentEquals(TimeUtils.getDIYDate("2018-01-01", "yyyy-MM-dd"),CommonConst.currentSysDate,dep);
                vos.add(new RecruitNumberVo(dep,y1,y2,y3));
            }
            response.setObj(vos);
            response.setMsg("查询成功");
        }catch (Exception e){
            e.printStackTrace();
            return new ApiResponse(-1,"服务器错误");
        }
        return response;
    }

    @Override
    public ApiResponse getRecruitSource() {
        ApiResponse  response = new ApiResponse();
        try {
            List<ChartVO> vos = employeeRepository.countRecruitSource();
            response.setMsg("查询成功");
            response.setObj(vos);
        }catch (Exception e){
            e.printStackTrace();
            return new ApiResponse(-1,"服务器错误");
        }
        return response;
    }

    @Override
    public ApiResponse getHrEducation() {
        ApiResponse  response = new ApiResponse();
        try {
            List<ChartVO> vos = employeeRepository.countHrEducation();
            response.setMsg("查询成功");
            response.setObj(vos);
        }catch (Exception e){
            e.printStackTrace();
            return new ApiResponse(-1,"服务器错误");
        }
        return response;
    }

    @Override
    public ApiResponse getHrSalary() {
        ApiResponse response = new ApiResponse();
        try {
            //发放进度 总工资
            Long salarySum = employeeRepository.sumSalary();
            //平均工资
            Double salaryAvg = employeeRepository.avgSalaryAll();
            salarySum =  salarySum/10000;//转成万元
            salaryAvg = salaryAvg/10000;
            DecimalFormat df = new DecimalFormat("#.00");
            Map map = new HashMap();
            map.put("sum",df.format(salarySum));
            map.put("avg",df.format(salaryAvg));
            response.setObj(map);
            response.setMsg("查询成功");
        }catch (Exception e){
            e.printStackTrace();
            return new ApiResponse(-1,"服务器错误");
        }
        return response;
    }

    @Override
    public ApiResponse getHrDeptSalary() {
        ApiResponse response = new ApiResponse();
        try {

            //全部部门
            List<String> types = employeeRepository.selectAllDepartment();
            //平均工资
            List<Double> values = new ArrayList<>();
            for (String dep :
                    types) {
                Double avg = employeeRepository.avgSalaryByDepartment(dep);
                values.add(avg);
            }
            Map map = new HashMap();
            map.put("types",types);
            map.put("values",values);
            response.setObj(map);
            response.setMsg("查询成功");
        }catch (Exception e){
            e.printStackTrace();
            return new ApiResponse(-1,"服务器错误");
        }
        return response;
    }

    @Override
    public ApiResponse getRecruitSex() {
        ApiResponse response = new ApiResponse();
        try {
            //全部部门
            List<String> deps = employeeRepository.selectAllDepartment();
            List<RecruitSexVo> vos = new ArrayList<>();
            for (int i = 0; i < deps.size(); i++) {
                String dep = deps.get(i);
                //男
                Long M = employeeRepository.countAllByDepartmentAndSexAndDateOfTerminationIsNull(dep,"M");
                //女
                Long F  = employeeRepository.countAllByDepartmentAndSexAndDateOfTerminationIsNull(dep,"F");
                vos.add(new RecruitSexVo(dep,M,F));
            }
            response.setObj(vos);
            response.setMsg("查询成功");
        }catch (Exception e){
            e.printStackTrace();
            return new ApiResponse(-1,"服务器错误");
        }
        return response;
    }

    @Override
    public ApiResponse getTalentDeptEdu() {
        ApiResponse response = new ApiResponse();
        try {
            //全部部门
            List<String> deps = employeeRepository.selectAllDepartment();
            //全部学历
            List<String> edus = employeeRepository.selectAllEducation();
            List<TalentEduVo> vos = new ArrayList<>();
            for (int i = 0; i < deps.size(); i++) {
                String dep = deps.get(i);
                List<ChartVO> chartVOS = employeeRepository.countHrEducationByDepartment(dep);
                TalentEduVo temp =  new TalentEduVo();
                temp.setDepartment(dep);
                for (ChartVO vo :
                        chartVOS) {
                    Long value = vo.getValue();
                    if (vo.getName().equals(edus.get(0))) {
                        temp.setEdu1(value);
                    }
                    if (vo.getName().equals(edus.get(1))) {
                        temp.setEdu2(value);
                    }
                    if (vo.getName().equals(edus.get(2))) {
                        temp.setEdu3(value);
                    }
                    if (vo.getName().equals(edus.get(3))) {
                        temp.setEdu4(value);
                    }
                }
                vos.add(temp);
            }
            response.setObj(vos);
            response.setMsg("查询成功");
        }catch (Exception e){
            e.printStackTrace();
            return new ApiResponse(-1,"服务器错误");
        }
        return response;
    }

    @Override
    public ApiResponse getEduAvgSalary() {
        ApiResponse response = new ApiResponse();
        try {

            //全部学历
            List<String> edus = employeeRepository.selectAllEducation();
            //平均工资
            List<Double> values = new ArrayList<>();
            for (String edu :
                    edus) {
                Double avg = employeeRepository.avgSalaryByEducation(edu);
                avg =  avg/10000;//转成万元
                DecimalFormat df = new DecimalFormat("#.00");
                values.add(Double.valueOf(df.format(avg)));
            }
            Map map = new HashMap();
            map.put("types",edus);
            map.put("values",values);
            response.setObj(map);
            response.setMsg("查询成功");
        }catch (Exception e){
            e.printStackTrace();
            return new ApiResponse(-1,"服务器错误");
        }
        return response;
    }

    @Override
    public ApiResponse getPerfScore() {
        ApiResponse response = new ApiResponse();
        try {

            //全部部门
            List<String> deps = employeeRepository.selectAllDepartment();
            //平均绩效
            List<Double> values = new ArrayList<>();
            for (String dep :
                    deps) {
                Double avg = employeeRepository.avgPerfByDept(dep);
                values.add(avg);
            }
            Map map = new HashMap();
            map.put("types",deps);
            map.put("values",values);
            response.setObj(map);
            response.setMsg("查询成功");
        }catch (Exception e){
            e.printStackTrace();
            return new ApiResponse(-1,"服务器错误");
        }
        return response;
    }

    @Override
    public ApiResponse getDeptNumber(String time) {
        ApiResponse response = new ApiResponse();
        if (!TimeUtils.isDatePattern(time)) {
            return new ApiResponse(-1, "时间数据不对");
        }
        Date startTime = TimeUtils.getDateByString(time);
        //全部部门
        List<String> deps = employeeRepository.selectAllDepartment();
        //平均绩效
        List<Long> values = new ArrayList<>();
        for (String dep :
                deps) {
            Long sum = employeeRepository.countAllByDateOfHireAfterAndDateOfTerminationIsNotNullAndDepartmentEquals(startTime,dep);
            values.add(sum);
        }
        Map map = new HashMap();
        map.put("types",deps);
        map.put("values",values);
        response.setObj(map);
        response.setMsg("查询成功");
        response.setObj(map);
        return response;
    }

    /**
     * 获取利率
     *
     * @param thisSum
     * @param lastSum
     * @return
     */
    private String getRate(Long thisSum, Long lastSum) {
        BigDecimal a = new BigDecimal((thisSum - lastSum));
        BigDecimal b = new BigDecimal(lastSum);
        if (b.compareTo(BigDecimal.ZERO) == 0) {
            //如果被除数为0
            return  "0%";
        }
        String growthRate = a.divide(b).multiply(BigDecimal.valueOf(100)) + "%";
        return growthRate;
    }

    /**
     * 获取利率并分正负
     *
     * @param thisSum
     * @param lastSum
     * @return
     */
    private Map getRateMap(Long thisSum, Long lastSum) {
        Map map = new HashMap();

        BigDecimal a = new BigDecimal((thisSum - lastSum));
        BigDecimal b = new BigDecimal(lastSum);
        if (b.compareTo(BigDecimal.ZERO) == 0) {
            //如果被除数为0
            map.put("lift", 1);
            map.put("rate", "0%");
            return map;
        }
        BigDecimal res = a.divide(b, 2).multiply(BigDecimal.valueOf(100)).abs();
        if (res.compareTo(BigDecimal.ZERO) == -1) {
            //小于0 0代表下降
            map.put("lift", 0);
        } else {
            map.put("lift", 1);
        }
        String growthRate = res + "%";
        map.put("rate", growthRate);
        return map;
    }

}
